//
//  PostViewController.m
//  AgriMobile
//
//  Created by 春名 啓作 on 11/05/15.
//  Copyright 2011 e-agri. All rights reserved.
//

#import "PostViewController.h"
#import "HttpMethod.h"

@implementation PostViewController

@synthesize topicId;

UIButton *targetButton = nil;
NSString *targetButtonName = nil;
BOOL img1Selected = NO;
BOOL img2Selected = NO;
BOOL img3Selected = NO;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	UIBarButtonItem *button = [[[UIBarButtonItem alloc]
								initWithTitle:@"登録"
								style:UIBarButtonItemStyleBordered
								target:self
								action:@selector(postTopic)] autorelease];
	self.navigationItem.rightBarButtonItem = button;

	imgBtn1.tag = ImgButton1;	
	imgBtn2.tag = ImgButton2;
	imgBtn3.tag = ImgButton3;
	
	NSLog(@"PostView topicId:%@", topicId);
	if([topicId rangeOfString:@"target_c_commu_topic_id"].location == NSNotFound
	&& [topicId rangeOfString:@"target_c_diary_id"].location == NSNotFound
	&& [topicId rangeOfString:@"target_c_album_id"].location == NSNotFound){
		txtTitle.hidden = NO;
	}else {
		txtTitle.hidden = YES;
		
		if([topicId rangeOfString:@"target_c_album_id"].location != NSNotFound){
			txtTitle.text = self.title;
		}
	}

	if ([topicId isEqualToString:@"a=page_fh_diary_list"]) {
		lblCategory.hidden = NO;
		btnCategory.hidden = NO;
		lblPublishCaption.hidden = NO;
		lblPublishValue.hidden = NO;
		btnPublish.hidden = NO;

		[btnCategory addTarget:self action:@selector(chooseCategory:) forControlEvents:UIControlEventTouchDown];
		[btnPublish addTarget:self action:@selector(choosePublish:) forControlEvents:UIControlEventTouchDown];
	} else {
		lblCategory.hidden = YES;
		btnCategory.hidden = YES;
		lblPublishCaption.hidden = YES;
		lblPublishValue.hidden = YES;
		btnPublish.hidden = YES;
	}
}

- (IBAction)chooseCategory:(id)sender {
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"確認"
												   message:@"カテゴリ"
												  delegate:nil
										 cancelButtonTitle:@"OK"
										 otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (IBAction)choosePublish:(id)sender {

	StaticPickerController* pic = [[[StaticPickerController alloc] initWithNibName:@"StaticPickerView" bundle:nil] retain];
	pic.dataCaptions = [NSArray arrayWithObjects:@"全員に公開",@"マイフレンドまで公開",@"公開しない", nil];
	pic.dataValues = [NSArray arrayWithObjects:@"public", @"friend", @"private", nil];
	pic.srcLabelCaption = lblPublishCaption;
	pic.srcLabelValue = lblPublishValue;
	pic.view.center = self.view.center;

	[self.view addSubview:pic.view];
	[pic release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (IBAction)postTopic {

	[txtBody resignFirstResponder];
	[txtTitle resignFirstResponder];
	
	if ([txtBody.text length] == 0) {
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"確認"
													   message:@"本文を入力してください"
													  delegate:nil
											 cancelButtonTitle:@"OK"
											 otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"確認"
						  message:@"登録してもよろしいですか？"
						  delegate:self
						  cancelButtonTitle:@"OK"
						  otherButtonTitles:@"Cencel",nil];
	[alert show];
	[alert release];
}

- (void)alertView:(UIAlertView*) alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

	NSString *btnName = @"";
	switch (buttonIndex) {
		case 0:
			btnName = @"OK";
			[self submitPost];

			break;
		case 1:
			btnName = @"Cancel";
			break;
		default:
			break;
	}

	/*
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ボタン"
												   message:btnName
												  delegate:nil
										 cancelButtonTitle:@"OK"
										 otherButtonTitles:nil];
	[alert show];
	[alert release];
	*/

}

- (void)submitPost {

	NSString *boundary = [[[NSNumber alloc]initWithInt:(UInt64)floor(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970)] stringValue];
    NSMutableData* result = [[NSMutableData alloc] init];

	//action(a)
	[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
	[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"a\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
	[result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
	[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];	
	[result appendData:[[NSString stringWithFormat:@"%@", @"post_topic"] dataUsingEncoding:NSASCIIStringEncoding]];
	[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

	//title
    [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"title\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"%@",txtTitle.text] dataUsingEncoding:NSUTF8StringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

	//body
    [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"body\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"%@",txtBody.text] dataUsingEncoding:NSUTF8StringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

	//topicId
    [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"topicId\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithFormat:@"%@",topicId] dataUsingEncoding:NSASCIIStringEncoding]];
    [result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
	
	//For diary only
	if ([topicId isEqualToString:@"a=page_fh_diary_list"]) {
		//Publish
		[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"public_flag\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"%@",lblPublishValue.text] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];

		//Category
		[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"category\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Type: text/plain; charset=utf-8\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"%@",lblCategory.text] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
	}

	//Image
	if( img1Selected ){
		NSLog(@"file1 uploading");
		[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file1\"; filename=\"%@\"\r\n", @"file1.jpg"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSData alloc]initWithData:UIImagePNGRepresentation([imgBtn1 backgroundImageForState:UIControlStateNormal])]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		//[result appendData:[[NSString stringWithFormat:@"--%@--\r\n\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
	}
	if( img2Selected ){
		NSLog(@"file2 uploading");
		[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file2\"; filename=\"%@\"\r\n", @"file2.jpg"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSData alloc]initWithData:UIImagePNGRepresentation([imgBtn2 backgroundImageForState:UIControlStateNormal])]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		//[result appendData:[[NSString stringWithFormat:@"--%@--\r\n\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
	}
	if( img3Selected ){
		NSLog(@"file3 uploading");
		[result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file3\"; filename=\"%@\"\r\n", @"file3.jpg"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		[result appendData:[[NSData alloc]initWithData:UIImagePNGRepresentation([imgBtn3 backgroundImageForState:UIControlStateNormal])]];
		[result appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
		//[result appendData:[[NSString stringWithFormat:@"--%@--\r\n\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
	}
	[result appendData:[[NSString stringWithFormat:@"--%@--\r\n\r\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];

	HttpMethod *http = [HttpMethod alloc];
	NSString *resp = [http doGet:[[NSString alloc] initWithFormat:@"%@/post.jsp",URLRoot]];
	[http release];
	NSRange actionRangeStart = [resp rangeOfString:@"/_ah/"];
	NSRange actionRangeEnd = [resp rangeOfString:@"method="];
	NSString *formAction = [resp substringWithRange:NSMakeRange(actionRangeStart.location,
										actionRangeEnd.location-actionRangeStart.location-2)];
	NSLog(@"action=[%@]", formAction);

    // リクエストの作成
    NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:@"%@%@",URLRoot,formAction]];
    //NSString *header = [[NSString alloc] initWithFormat:@"OAuth %@", [consumer getToken]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    //[request setValue:header forHTTPHeaderField:@"Authorization"];
    [request setHTTPBody:result];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

    NSURLResponse *response = nil;
    NSError       *error    = nil;
    //NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


	NSArray *allConts = self.navigationController.viewControllers;
	UITableViewController *parent = [allConts objectAtIndex:[allConts count] - 2];
	[parent.tableView reloadData];
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showCameraSheet:(id)sender {

	[txtBody resignFirstResponder];
	[txtTitle resignFirstResponder];

	
	if([sender tag] == ImgButton1) {
		targetButton = imgBtn1;
		targetButtonName = @"imgBtn1";
	}else if ([sender tag] == ImgButton2) {
		targetButton = imgBtn2;
		targetButtonName = @"imgBtn2";
	}else if ([sender tag] == ImgButton3) {
		targetButton = imgBtn3;
		targetButtonName = @"imgBtn3";
	}
	NSLog(@"%@ clicked.", targetButtonName);
	
	UIActionSheet *camSheet = [[[UIActionSheet alloc]initWithTitle:@"写真の選択"
						delegate:self
						cancelButtonTitle:@"キャンセル"
						destructiveButtonTitle:nil
						otherButtonTitles:@"保存されている写真", @"フォトアルバム", @"カメラで撮る",nil]autorelease];
	//[camSheet showInView:self.view];
	[camSheet showFromTabBar:super.view];
}


- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	if (buttonIndex >= 3) {
		return;
	}
	
	UIImagePickerControllerSourceType sourceType = 0;
	NSString *sourceTypeName = @"";
	switch (buttonIndex) {
		case 0:
			sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
			sourceTypeName = @"保存されている写真";
			break;
		case 1:
			sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			sourceTypeName = @"フォトライブラリ";
			break;
		case 2:
			sourceType = UIImagePickerControllerSourceTypeCamera;
			sourceTypeName = @"カメラ";
			break;
		default:
			break;
	}
	
	if(![UIImagePickerController isSourceTypeAvailable:sourceType]){
		UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle:@"現在使用できません"
							  message:[[NSString alloc]initWithFormat:@"%@を使用できません",sourceTypeName]
							  delegate:nil
							  cancelButtonTitle:@"OK"
							  otherButtonTitles:nil
							  ];
		[alert show];
		[alert release];
		return;
	}
	
	UIImagePickerController *img = [[[UIImagePickerController alloc] init] autorelease];
	img.sourceType = sourceType;
	//img.allowsImageEditing = NO;
	img.delegate = self;
	
	[self presentModalViewController:img animated:YES];
}

- (void)imagePickerController:(UIImagePickerController*)picker
		didFinishPickingImage:(UIImage*)orgImage
		editingInfo:(NSDictionary*)editingInfo {

	[self dismissModalViewControllerAnimated:YES];

	float ratio = 1.0;
	if (orgImage.size.width * orgImage.size.height > 60000.0){
		ratio = 60000.0 * 10 / (orgImage.size.width * orgImage.size.height);
	}

	UIImage* resizedImage = [self resizeImage:orgImage resizeRatio:ratio];

	[targetButton setImage:nil forState:UIControlStateNormal];
	[targetButton setBackgroundImage:resizedImage forState:UIControlStateNormal];

	if (targetButton == imgBtn1) {
		img1Selected = YES;
	}else if (targetButton == imgBtn2) {
		img2Selected = YES;
	}else if (targetButton == imgBtn3) {
		img3Selected = YES;
	}

	NSLog(@"%@ changed.", targetButtonName);
}

- (UIImage*)resizeImage:(UIImage*)image resizeRatio:(float)ratio
{
	NSLog(@"resizeImage ratio:%f", ratio);

	int wid = (int)((float)image.size.width * (float)ratio);
	int hgt = (int)((float)image.size.height * (float)ratio);
	NSLog(@"resizeImage from[%f, %f] to [%d, %d]", image.size.width, image.size.height, wid, hgt);

	CGRect frame = CGRectMake(0, 0, wid, hgt);
	UIGraphicsBeginImageContext(frame.size);
	[image drawInRect:frame];
	UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return resizedImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker {

	[self dismissModalViewControllerAnimated:YES];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	[textField resignFirstResponder];
	return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}


@end
